package com.cooksys.film_rental.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.cooksys.film_rental.dao.FilmActorDao;
import com.cooksys.film_rental.model.Actor;
import com.cooksys.film_rental.model.Film;
import com.cooksys.film_rental.model.FilmActor;
import com.cooksys.film_rental.model.FilmActorId;

@Repository("FilmActorDao")
@Transactional
public class FilmActorDaoImpl implements FilmActorDao {

	@Autowired(required = true)
	private SessionFactory sessionFactory;

	/**
	 * 
	 * @return the current session from the internal {@link SessionFactory}
	 */
	public Session currentSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public void save(FilmActor filmActor) {
		Session session = currentSession();
		session.save(filmActor);

	}

	@Override
	public void update(FilmActor filmActor) {
		Session session = currentSession();
		session.update(filmActor);

	}

	@Override
	public void delete(FilmActor filmActor) {
		Session session = currentSession();
		session.delete(filmActor);

	}

	@Override
	public FilmActor getFilmActorByFilmActorId(FilmActorId filmActorId) {
		Session session = currentSession();

		String hql = "from FilmActor f where f.id = :filmActorId";
		Query query = session.createQuery(hql);

		query.setEntity("filmActorId", filmActorId);

		return (FilmActor) query.list().get(0);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<FilmActor> searchFilmActorsByFilm(Film film) {
		Session session = currentSession();
		
		// selects a list of FilmActor objects associated with the given film
		String hql = "from FilmActor f where f.film = :film";
		Query query = session.createQuery(hql);

		query.setEntity("film", film);

		return query.list();
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<FilmActor> searchFilmActorsByActor(Actor actor) {
Session session = currentSession();
		
		// selects a list of FilmActor objects associated with the given actor
		String hql = "from FilmActor f where f.actor = :actor";
		Query query = session.createQuery(hql);

		query.setEntity("actor", actor);

		return query.list();
	}

}
